package vo

import (
	"fmt"
	"lnzw/engine/net/marshal"
	"lnzw/engine/net/tcp"
	"sync/atomic"
	"time"
)

type Robot struct {
	Id     int64
	client *tcp.ServerClient
}

type MySocketHandle struct {
}

func (m *MySocketHandle) OnConnect(client *tcp.SocketClient) {
	fmt.Println("client OnConnect")
}

func (m *MySocketHandle) OnMessage(client *tcp.SocketClient, data []byte) {
	fmt.Println("client OnMessage")
}

func (m *MySocketHandle) OnClose(client *tcp.SocketClient) {
	fmt.Println("client OnClose")
}

var robotInitId int64

func init() {
	robotInitId = time.Now().UnixNano()
}

func increateAndGetId() int64 {
	atomic.AddInt64(&robotInitId, 1)
	return robotInitId
}

func NewRobot() *Robot {
	return &Robot{Id: increateAndGetId(), client: tcp.NewServerClient()}
}

func (r *Robot) Start() {
	r.client.BindAddress(":8080").
		BindSocketHandle(&MySocketHandle{}).
		Decoder(&marshal.VariableDecode{FirstRecevedLen: marshal.FirstLen_4}).
		Encoder(&marshal.VariableEncode{FirstSendLen: marshal.FirstLen_4})
	r.client.Start()
	go r.Test()
}

// 暂时测试是否解决了粘包半包问题
func (r *Robot) Test() {
	for {
		//value := stringutils.RandomString(10, 20)
		// r.client.SendPb(int32(cs_gen.ReqLogin_ID), &cs_gen.ReqLogin{Account: stringutils.RandomString(1, 5), Password: stringutils.RandomString(1, 5)})
		// time.Sleep(time.Second)
	}
}
